from datetime import datetime
from datetime import timedelta

import os
from google.appengine.ext.webapp import template

import cgi

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db


class Board(db.Model):
    identifier = db.StringProperty()
    author = db.UserProperty(required=True)
    title = db.StringProperty(required=True)
    description = db.StringProperty(multiline=True)
    deadline = db.DateTimeProperty()
    closed = db.BooleanProperty()
    created_at = db.DateTimeProperty(auto_now_add=True)
    updated_at = db.DateTimeProperty(auto_now=True)

class Post(db.Model):
    identifier = db.StringProperty()
    board = db.ReferenceProperty(Board, required=True)
    author = db.UserProperty(required=True)
    message = db.StringProperty(multiline=True)
    created_at = db.DateTimeProperty(auto_now_add=True)
    updated_at = db.DateTimeProperty(auto_now=True)


def renderPortion(request_handler, partial_html, template_values):
    template_values['content'] = partial_html
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    request_handler.response.out.write(template.render(path, template_values))

def getJSTimeComponents(date_obj):
    components = date_obj.strftime("%Y,%m,%d,%H,%M,%S")
    # decrement month by 1, since Javascript Date starts from month 0
    components = components.split(',')
    components[1] = str(int(components[1]) - 1)
    components = ','.join(components)
    return components


class MainPage(webapp.RequestHandler):

    def get(self):
        boards = Board.all()
        boards.order('-created_at')

        current_user = users.get_current_user()
        if current_user:
            logged_in = True
            url = users.create_logout_url(self.request.uri)
        else:
            logged_in = False
            url = users.create_login_url(self.request.uri)

        now = datetime.now()
        template_values = {
            'systemtime_components': getJSTimeComponents(now),
            'boards': boards.fetch(10),
            'current_user': current_user,
            'logged_in': logged_in,
            'url': url,
            }

        renderPortion(self, 'main.html', template_values)


class CreateBoard(webapp.RequestHandler):

    def post(self):
        if not users.get_current_user():
            self.redirect('/')
            return

        board = Board(
                      author = users.get_current_user(),
                      title = self.request.get('title'),
                      description = self.request.get('description'),
                      closed = False
                      )

        timezone_offset = 0
        if self.request.get('deadline_timezone'):
            timezone_offset = int(self.request.get('deadline_timezone'))
        if self.request.get('deadline_timestamp'):
            deadline_timestamp = datetime.strptime(self.request.get('deadline_timestamp'), "%Y-%m-%d %H:%M:%S")
            timezone_delta = timedelta(seconds = (timezone_offset * 3600))
            board.deadline = deadline_timestamp - timezone_delta
        board.put()
        self.redirect('/')


class ViewBoard(webapp.RequestHandler):

    def get(self):
        key = self.request.get('key')
        board = Board.get(key)
        posts = Post.all().filter('board =', board).order('created_at').fetch(1000)

        current_user = users.get_current_user()
        if current_user:
            logged_in = True
            url = users.create_logout_url(self.request.uri)
        else:
            logged_in = False
            url = users.create_login_url(self.request.uri)

        now = datetime.now()
        countdown_seconds = 0
        deadline_components = None
        if board.deadline and board.deadline < now:
            board.closed = True
            board.put()

        delta = (board.deadline - now)
        countdown_seconds = delta.seconds
        deadline_components = board.deadline.strftime("%Y, ")
        deadline_components += str(int(board.deadline.strftime("%m")) - 1)
        deadline_components += board.deadline.strftime(", %d, %H, %M, %S")

        template_values = {
#            'systemtime': now.strftime("%a, %d %b %Y %H:%M:%S %Z"),
            'systemtime_components': getJSTimeComponents(now),
            'countdown_seconds': countdown_seconds,
            'key': key,
            'board': board,
            'posts': posts,
            'deadline': board.deadline,
            'deadline_components': deadline_components,
            'current_user': current_user,
            'logged_in': logged_in,
            'url': url,
            'title': board.title,
            }

        renderPortion(self, 'board.html', template_values)


class PostMessage(webapp.RequestHandler):

    def post(self):
        if not users.get_current_user():
            self.redirect('/')
            return

        post = Post(
                    board = Board.get(self.request.get('key')),
                    author = users.get_current_user(),
                    message = self.request.get('message'),
                    )
        post.put()

        self.redirect('/board?key=%s' % self.request.get('key'))


application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/create_board', CreateBoard),
                                      ('/board', ViewBoard),
                                      ('/post_message', PostMessage)],
                                     debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
